package com.csu.analysis.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.csu.analysis.service.MeasureService;
import com.csu.device.dao.BehaviorDao;
import com.csu.device.entity.Behavior;
import com.csu.device.entity.Device;
import com.csu.device.entity.DeviceRela;
import com.csu.device.service.HardWareService;
import com.csu.push.AppPush;
import com.csu.push.HttpMessagePush;
import com.csu.push.WebSocketPush;
import com.csu.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class MeasureServiceImpl implements MeasureService {


    @Autowired
    private HardWareService hardWareService;


    @Autowired
    private BehaviorDao behaviorDao;

    /**
     * 血压
     *
     * @param data 90mmHg<高压<140mmHg、60mmHg<低压<90mmHg、心率：60～100次/分
     *             {T=2838,P=997,H=5115}
     */
    @Override
    public JSONObject sphygmomanometer(String data, String deviceSn, String ifid) {
        double g = Double.parseDouble(data.split(",")[0]);
        double d = Double.parseDouble(data.split(",")[1]);
        double x = Double.parseDouble(data.split(",")[2]);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dtype", "sphygmomanometer");
        jsonObject.put("g", g);
        jsonObject.put("d", d);
        jsonObject.put("x", x);
        StringBuffer message = new StringBuffer();
        message.append("高压:" + g);
        message.append("  低压:" + d);
        message.append("  心跳:" + x);
        if (g < 90 || g > 140 || d < 60 || d > 90) {
            jsonObject.put("anomalies", 1);
        } else {
            jsonObject.put("anomalies", 0);
        }
        jsonObject.put("message", message.toString());
        this.addBehavior(jsonObject, deviceSn, ifid);
        return jsonObject;
    }

    /**
     * 血氧
     *
     * @param data "deviceData":"112,99"
     */
    @Override
    public JSONObject oximeter(String data, String deviceSn,String ifid) {
        Double heartRate  = Double.parseDouble(data.split(",")[0]);
        Double oximeter = Double.parseDouble(data.split(",")[1]);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dtype", "oximeter");
        jsonObject.put("oximeter", oximeter);
        jsonObject.put("heartRate", heartRate);
        if (oximeter < 94 || heartRate < 60 || heartRate > 100) {
            jsonObject.put("anomalies", 1);
        } else {
            jsonObject.put("anomalies", 0);
        }
        jsonObject.put("message", "血氧值:" + oximeter + "心跳值:" + heartRate);
        this.addBehavior(jsonObject, deviceSn, ifid);
        return jsonObject;
    }

    /**
     * 耳温枪
     *
     * @param data
     */
    @Override
    public JSONObject thermometer(String data, String deviceSn, String ifid) {
        double her = Double.parseDouble(data);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dtype", "thermometer");
        jsonObject.put("her", her);
        if (her < 36.1 || her > 37) {
            jsonObject.put("anomalies", 1);
        } else {
            jsonObject.put("anomalies", 0);
        }
        jsonObject.put("message", "当前体温:" + her);
        this.addBehavior(jsonObject, deviceSn, ifid);
        return jsonObject;
    }

    /**
     * 血糖
     * @param data
     * @param deviceSn
     * @param ifid
     * @return
     */
    @Override
    public JSONObject glucometer(String data, String deviceSn, String ifid) {
        double glucometer = Double.parseDouble(data);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dtype", "glucometer");
        jsonObject.put("glucometer", glucometer);
        if (glucometer < 3.9 || glucometer > 7.0) {
            jsonObject.put("anomalies", 1);
        } else {
            jsonObject.put("anomalies", 0);
        }
        jsonObject.put("message", "当前血糖:" + glucometer);
        this.addBehavior(jsonObject, deviceSn, ifid);
        return jsonObject;
    }


    private void pushMessage(JSONObject jsonObject, String ifid,String deviceSn) {
        try {
            if (!"".equals(ifid)) {//刷卡设备
                //remark 根据remark 查询对于的老人
                String userId = this.getUserIdByIfid(ifid);
                jsonObject.put("userId", userId);
                HttpMessagePush.measurePush(jsonObject);
            } else {
                Device device = (Device) RedisUtil.get(deviceSn);
                if (null == device) {
                    return;
                }
                //根据设备绑定的数据推送
                WebSocketPush.measurePush(jsonObject, device.deviceRelas, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 体征检测设备保存
     *
     * @param jsonObject
     * @param deviceSn
     * @param ifid
     */
    public void addBehavior(JSONObject jsonObject, String deviceSn, String ifid) {
        Device device = (Device) RedisUtil.get(deviceSn);
        if (null == device) return;
        Behavior behavior = hardWareService.getDevRelaToDo(device.getDeviceRelas(), deviceSn);
        if (behavior.getFamilyUserId() == null) {
            behavior.setFamilyUserId(this.getUserIdByIfid(ifid));
            behavior.setFamilyUserName(this.getUserNameByIfid(ifid));
        }
        behavior.setDataValue(jsonObject.toJSONString());
        behavior.setAnomalies(jsonObject.getInteger("anomalies"));
        behavior.setBehaviorType(0);
        behavior.setStartTime(new Date());
        behavior.setRemark(jsonObject.getString("message"));
        behavior.setLevel(2);

        //页面推送
        WebSocketPush.sendAppUserMessageByMeasure(behavior);
        behavior.setApplicationId(null);
        behaviorDao.addBehavior(behavior);

        if(behavior.getAnomalies()==0){
            this.pushMessage(jsonObject,ifid,deviceSn);
        }if(behavior.getAnomalies()==1){
            this.pushMessage(jsonObject,ifid,deviceSn);
            WebSocketPush.errorPush(behavior);
            AppPush.pushToSingle(behavior.getFamilyUserId(), "体征检测异常",behavior.getRemark(),2);
        }

    }

    /**
     * IFID转化为userId
     *
     * @param remark
     * @return
     */
    private String getUserIdByIfid(String remark) {
        String userId = "";
        Device user = (Device) RedisUtil.get(remark);
        if (null == user) {
            return null;
        }
        //获取绑定的老人信息
        for (DeviceRela rela : user.getDeviceRelas()) {
            if (rela.getBindingType() == 1) {
                userId = rela.getDeviceBindingId();
            }
        }
        return userId;
    }


    /**
     * IFID转化为userId
     *
     * @param remark
     * @return
     */
    private String getUserNameByIfid(String remark) {
        String userName = "";
        Device user = (Device) RedisUtil.get(remark);
        if (null == user) {
            return null;
        }
        //获取绑定的老人信息
        for (DeviceRela rela : user.getDeviceRelas()) {
            if (rela.getBindingType() == 1) {
                userName = rela.getName();
            }
        }
        return userName;
    }


}
